<template>
  <div>
    <div>* 平台分类数据已经由<a href="//spider.beijingzhuyou.com" target="_blank">专有爬虫</a>接管</div>
    <el-form label-width="100px">
      <el-form-item label="选择日期范围">
        <el-date-picker
                v-model="filter.date"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                @change="changeDate"
                :picker-options="dateOption">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="搜索">
        <el-autocomplete clearable
                         placeholder="请输入内容"
                         style="width: 200px"
                         @select="selectCategory"
                         :fetch-suggestions="searchTypes"/>
      </el-form-item>
      <el-form-item label="查询历史" v-show="history.length > 0">
        <el-radio-group v-model="filter.selected">
          <el-radio-button v-for="c in history" :label="c" :key="c.id">{{c.value}}</el-radio-button>
        </el-radio-group>
        <el-button @click="clearHistory">清空历史</el-button>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="!filter.date  || !filter.selected" @click="loadTypeData"
                   type="success">获取数据
        </el-button>
      </el-form-item>
    </el-form>
    <el-tabs>
      <el-tab-pane label="数据图">
        <div class="chart_group">
          <div class="chart_item" ref="chartActive"></div>
          <div class="chart_item" ref="chartNew"></div>
          <div class="chart_item" ref="chartOpen"></div>
          <div class="chart_item" ref="chartWatch"></div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="数据表">
        <template v-for="t in tableDataIndex">
          <h2>{{t.title}}</h2>
          <el-table border stripe :data="table.data">
            <el-table-column label="日期" prop="date"/>
            <template v-for="p in platforms">
              <el-table-column :label="p.name" :prop="t.index + '[' + p.id + ']'"/>
            </template>
          </el-table>
          <hr>
        </template>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  const defaultData = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985',
        },
      },
    },
    toolbox: {right: '10%', feature: {saveAsImage: {pixelRatio: 2}}},
    grid: {
      top: '30%',
      bottom: '0%',
      containLabel: true,
    },
    legend: {top: '8%', right: '20%'},
    yAxis: {},
  };

  let chartActive, chartNew, chartOpen, chartWatch;
  export default {
    name: 'spiderTypeECharts',
    props: ['platforms'],
    data() {
      return {
        filter: {date: null, selected: null},
        history: [],
        table: {date: [], data: []},
        tableDataIndex: [
          {title: '活跃主播数量', index: 'num_active'},
          {title: '观看人数', index: 'num_watch'},
          {title: '主播开播数量', index: 'num_open'},
          {title: '主播新增数量', index: 'num_new'},
        ],
        dateOption: {
          shortcuts: [
            {
              text: '最近一周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              },
            }, {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              },
            }, {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit('pick', [start, end]);
              },
            }],
        },
      };
    },
    methods: {
      async searchTypes(search, cb) {
        if (_.isEmpty(search))
          return cb([]);
        const res = await this.$asyncHttp.get('/api/spider/types', {params: {search}});
        const repeat = {};
        res.data.forEach(item => {
          if (repeat[item.type.id])
            return;
          repeat[item.type.id] = {
            id: item.type.id,
            value: item.type.name,
          };
        });
        cb(Object.values(repeat));
      },
      selectCategory(category) {
        this.filter.selected = category;
        this.setHistory(category);
      },
      getHistory() {
        let history = window.localStorage.getItem('daily_category_history');
        if (history) {
          history = JSON.parse(history);
        }
        if (_.isArray(history))
          this.history = history;
      },
      setHistory(category) {
        if (_.find(this.history, category))
          return;
        this.history.push(category);
        window.localStorage.setItem('daily_category_history', JSON.stringify(this.history));
      },
      clearHistory() {
        localStorage.clear();
        this.history = [];
      },
      async loadTypeData() {
        let start = this.filter.date[0],
            end = this.filter.date[1],
            id = this.filter.selected.id;
        const res = await this.$asyncHttp.get(`/api/spider-types/data/${id}/${start}/${end}`);

        const data = res.data;
        this.loading = false;
        this.table = data.table;
        start = moment(start).format('YYYY-MM-DD');
        end = moment(end).format('YYYY-MM-DD');
        const {legend, xAxis, num_watch, num_open, num_active, num_new} = data.chart;
        chartWatch.setOption(Object.assign({
          title: {text: '观看人数'},
          legend,
          xAxis,
          series: num_watch,
          toolbox: {feature: {saveAsImage: {name: `观看人数 ${start} 到 ${end}`}}},
        }, defaultData));
        chartNew.setOption(_.merge({
          title: {text: '新增主播数量'},
          legend,
          xAxis,
          series: num_new,
          toolbox: {feature: {saveAsImage: {name: `新增主播数量 ${start} 到 ${end}`}}},
        }, defaultData));
        chartOpen.setOption(_.merge({
          title: {text: '主播开播数量'},
          legend,
          xAxis,
          series: num_open,
          toolbox: {feature: {saveAsImage: {name: `主播开播数量 ${start} 到 ${end}`}}},
        }, defaultData));
        chartActive.setOption(_.merge({
          title: {text: '活跃主播数量'},
          legend,
          xAxis,
          series: num_active,
          toolbox: {feature: {saveAsImage: {name: `活跃主播数量 ${start} 到 ${end}`}}},
        }, defaultData));
        chartActive.resize();
        chartNew.resize();
        chartOpen.resize();
        chartWatch.resize();
      },
      changeDate() {
        let result = false;
        if (!_.isEmpty(this.filter.date)) {
          let diff = moment(this.filter.date[1]).diff(moment(this.filter.date[0]), 'day');
          result = diff === 0;
        }
        console.log('isSameDay', this.filter.date, result);
        this.isSameDay = result;
      },
    },
    mounted() {
      this.getHistory();
      this.$nextTick(() => {
        chartActive = echarts.init(this.$refs['chartActive']);
        chartNew = echarts.init(this.$refs['chartNew']);
        chartOpen = echarts.init(this.$refs['chartOpen']);
        chartWatch = echarts.init(this.$refs['chartWatch']);
      });
    },
  };
</script>

<style scoped lang="scss">
  .chart_group {
    display: flex;
    flex-wrap: wrap;
    .chart_item {
      width: 50%;
      height: 400px;
    }
  }


</style>